package com.gxlu.ms.base.util;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

/**
 *
 * @author andy.lhc
 * @date 2018/3/18
 */
public class CommonUtil {


    /**
     * 解析 attribute的格式，统一如下格式存储
     * k1=v1;k2=v2;k3=v3
     * @param attribute
     * @return
     */
    public static  String getAttributeValue(String attribute,String key){
        if(StringUtils.isBlank(attribute) || StringUtils.isBlank(key) ){
            return  "";
        }
        Map<String,String> map = new HashMap<>(16);
        String[] array = attribute.split(";");
        if(array==null || array.length == 0){
            return  "";
        }
        for(String kv: array){
            String[] array2 = kv.split("=");
            if(array2!=null && array2.length==2){
                map.put(array2[0],array2[1]);
            }
        }
        return ( (map.isEmpty() || !map.containsKey(key)) ? "": map.get(key) ) ;
    }

    /**
     * map 解析成  k1=v1;k2=v2;k3=v3
     * @param map
     * @return
     */
    public static String getAttribute(Map<String,String> map){
        if(map==null ||map.isEmpty()){
            return  "";
        }
        StringBuilder sb = new StringBuilder();
        map.entrySet().stream().forEach(entry -> {
            sb.append(entry.getKey()+"="+entry.getValue());
            sb.append(";");
        });
        return  sb.toString();
    }


    /**
     * k1=v1;k2=v2 转成 Map
     * @param attribute
     * @return
     */
    public static Map<String,String> attributeToMap(String attribute){
        if(StringUtils.isBlank(attribute)){
            return  new HashMap<>(16);
        }
        Map<String,String> map = new TreeMap<>();
        String[] arrays = attribute.split(";");
        if(arrays==null || arrays.length == 0){
            return  new HashMap<>(16);
        }
        for(String attr : arrays){
            String[] array2 = attr.split("=");
            if(array2!=null && array2.length==2){
                map.put(array2[0],array2[1]);
            }
        }
        return map ;
    }


}
